import React, { useEffect, useRef, useState } from 'react';
import { Button, Cell, DatetimePicker, Form, Input, Switch } from 'react-vant'
import { WdSelectItem } from '../../../components/wd-select-item';
import { useBoolean, useRequest, useSetState } from 'ahooks';
import { getDiseaseContent, getDiseaseTitle } from '../../../api/home';
import { DiseaseContentState, DiseaseTitleState } from '../../home/knows';
import { addDiseaseItem, uploadImageDisease } from '../../../api/disease';
import { wrap } from 'module';
import { request } from '../../../service/request';



interface PropsType {
  handleUpload: (imageList: { base64: string, file: File }[]) => void
}
const UploadImage: React.FC<PropsType> = ({ handleUpload }) => {
  const [imageList, setImageList] = useState<{
    base64: string
    file: File
  }[]>([]);

  const inputEl = useRef<HTMLInputElement | null>(null);
  const onchange = () => {
    const input = inputEl.current as HTMLInputElement;
    const files = input.files
    if (!files) return;
    Array.from(files).map(v => {
      const reader = new FileReader();
      reader.readAsDataURL(v);
      reader.onload = () => {
        console.log(reader.result)
        setImageList((imageList) => {
          handleUpload([...imageList, { file: v, base64: reader.result as string }])

          return [...imageList, { file: v, base64: reader.result as string }]
        })
      }
    })
  }
  return <div>
    <div>
      <div style={{ display: 'flex', flexWrap: 'wrap' }}>
        {
          imageList.map((v, i) => {
            return <img src={v.base64} key={i} alt="" width="33.%" height="100" style={{ padding: 2 }} />
          })
        }
      </div>
      <button onClick={() => inputEl.current?.click()}>上传图片</button>
    </div>
    <input ref={inputEl} type="file" style={{ display: 'none' }} onChange={() => onchange()} multiple />
  </div >
};

interface DataState {
  // title	string	标题
  // departmentId	int	科室id
  // disease	string	病症描述
  // detail	string	病症详情
  // treatmentHospital	string	治疗医院
  // treatmentStartTime	String	治疗开始时间 格式’2018-3-26’
  // treatmentEndTime	String	治疗结束时间 格式’2018-6-26’
  // treatmentProcess	string	治疗过程描述
  // amount	int	悬赏额度，无时为0
  title: string	// 标题
  departmentId: number	//科室id
  disease: string //	病症描述
  detail: string	//病症详情
  treatmentHospital: string	//治疗医院
  treatmentStartTime: string	//治疗开始时间 格式’2018-3-26’
  treatmentEndTime: string	//治疗结束时间 格式’2018-6-26’
  treatmentProcess: string	//治疗过程描述
  amount: number	//悬赏额度，无时为0
}

const Index: React.FC = () => {
  const [type, setType] = useSetState({
    name: '请选择就诊科室',
    id: ''
  });
  const [disease, setDisease] = useSetState({
    name: '请选择主要病症',
    id: ''
  });

  const { data: typeTitles = [] } = useRequest(async () => {
    const resp = await getDiseaseTitle();
    return (resp.data.result.map(v => ({ name: v.departmentName, id: v.id.toString() }))) as { name: string, id: string }[]
  })

  const { data: diseaseTitles = [], run } = useRequest(async () => {
    const resp = await getDiseaseContent(+type.id);
    return resp.data.result.map(v => ({ name: v.name, id: v.id.toString() })) as { name: string, id: string }[];
  });

  useEffect(() => run(), [type])
  const [fileList, setFileList] = useState<File[]>([])
  const handleUpload = (imageList: { base64: string, file: File }[]) => {
    setFileList(imageList.map(v => v.file))
  }
  const onFinish = async (value: any) => {
    const data = {
      ...value,
      treatmentEndTime: new Date(value.treatmentEndTime).toLocaleDateString().replace(/\//g, '-'),
      treatmentStartTime: new Date(value.treatmentStartTime).toLocaleDateString().replace(/\//g, '-'),
      amount,
      departmentId: type.id,	//科室id
      disease: disease.name //	病症描述
    }
    // 调用接口
    addDiseaseItem(data).then(resp => {
      console.log(resp.data)
    })

    // const sickCircleId = 2587
    // const picture = fileList
    // const formData = new FormData();
    // formData.append('sickCircleId', '2587')
    // formData.append('picture', fileList[0])
    // const resp = await request.post('/api/health/user/sickCircle/verify/v1/uploadSickCirclePicture', formData, {
    //   headers: {
    //     "Content-Type": 'multipart/form-data'
    //   }
    // })

    // console.log(resp.data)
  }

  const [show, { toggle }] = useBoolean(true);
  const list = [10, 20, 30];
  const [amount, setAmount] = useState(0)
  return <Form onFinish={onFinish}>
    <Form.Item rules={[{ required: true, message: '标题不可以为空' }]} name="title">
      <Input placeholder='请输入标题(最多20字)'></Input>
    </Form.Item>
    <WdSelectItem content={type} list={typeTitles} onChange={(value) => setType(value)}></WdSelectItem>
    <WdSelectItem content={disease} list={diseaseTitles} onChange={(value) => setDisease(value)}></WdSelectItem>
    <Form.Item name='detail'>
      <Input.TextArea placeholder='请输入详细病症' rows={5} maxLength={300} showWordLimit />
    </Form.Item>
    <Form.Item name="treatmentHospital">
      <Input placeholder='请输入医院名称'></Input>
    </Form.Item>
    <Form.Item name="treatmentStartTime" trigger='onConfirm'
      onClick={(_, action) => {
        action!.current?.open()
      }}>
      <DatetimePicker popup type='date'>
        {(val: Date) => (val ? val.toLocaleString() : '请选择开始时间')}
      </DatetimePicker>
    </Form.Item>
    <Form.Item name="treatmentEndTime" trigger='onConfirm'
      onClick={(_, action) => {
        action!.current?.open()
      }}>
      <DatetimePicker popup type='date'>
        {(val: Date) => (val ? val.toLocaleString() : '请选择结束时间')}
      </DatetimePicker>
    </Form.Item>
    <Form.Item name="treatmentProcess">
      <Input.TextArea placeholder='请输入治疗过程' rows={5} showWordLimit />
    </Form.Item>
    <UploadImage handleUpload={handleUpload}></UploadImage>
    <Cell title='提升悬赏额度' value={<Switch checked={show} onClick={() => toggle()}></Switch>} />
    {
      show && <div style={{ padding: 10 }}>
        <div style={{ display: 'flex', justifyContent: "space-between" }}>
          {
            list.map((v, i) => {
              return <Button onClick={() => setAmount(v)} type={amount === v ? 'primary' : "default"} key={i}>{v}H币</Button>
            })
          }
        </div>
        <div style={{ marginTop: 10 }}>
          {/* <Button> */}
          <Input value={amount.toString()} onChange={(value) => setAmount(+value)} placeholder='自定义' style={{ border: '1px solid #ccc', height: 50 }}></Input>
          {/* </Button> */}
        </div>
      </div>
    }
    <Button type="primary" block round nativeType="submit">提交</Button>
  </Form>
}



export default Index
